// pages/userInfo/userInfo.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
      //选科
      mainSubjectList: [
        {
          id: 0,
          text: '物理'
        },
        {
          id: 1,
          text: '历史'
        }
      ],
      secondSubjectList: [
        {
          id: 0,
          text: '化学'
        },
        {
          id: 1,
          text: '生物'
        },
        {
          id: 2,
          text: '政治'
        },
        {
          id: 3,
          text: '地理'
        }
      ],

      // 用户科目
      mainSubject: '',
      secondSubject: [],
      userMainSubject: '',
      userSecondSubject: [],
      showSubject: false,
      
      name:'',
      src:'',
      //设置一个标志位 值为false 用于显示和隐藏数据
      isShow:false,
      userInfo:{},
      isLoading: false,
      score: '',
      ranking: '',
      subjectList: ['物理', '历史', '艺术', '体育'],
      subjects: [
        {
          id: 0,
          name: '物理'
        },
        {
          id: 1,
          name: '历史'
        },
        {
          id: 2,
          name: '艺术'
        },
        {
          id: 3,
          name: '体育'
        }
      ],
      index1: 0,

      provincesList: ['广东', '湖南', '江西', '浙江','河北','陕西','山西','新疆',
                      '辽宁','内蒙古','黑龙江','吉林','江苏','安徽','福建','山东',
                      '河南','湖北','广西','海南','四川','贵州','云南','西藏','甘肃',
                      '青海','宁夏'],
      provinces: [
        {
          id: 0,
          name: '广东'
        },
        {
          id: 1,
          name: '湖南'
        },
        {
          id: 2,
          name: '江西'
        },
        {
          id: 3,
          name: '浙江'
        },
        {
          id: 4,
          name: '河北'
        },
        {
          id: 5,
          name: '陕西'
        },
        {
          id: 6,
          name: '山西'
        },
        {
          id: 7,
          name: '新疆'
        }, 
        {
          id: 8,
          name: '辽宁'
        },
        {
          id: 9,
          name: '内蒙古'
        },
        {
          id: 10,
          name: '黑龙江'
        },
        {
          id: 11,
          name: '吉林'
        },
        {
          id: 12,
          name: '江苏'
        },
        {
          id: 13,
          name: '安徽'
        },
        {
          id: 14,
          name: '福建'
        },
        {
          id: 15,
          name: '山东'
        }, 
        {
          id: 16,
          name: '河南'
        },
        {
          id: 17,
          name: '湖北'
        },
        {
          id: 18,
          name: '广西'
        },
        {
          id: 19,
          name: '海南'
        },
        {
          id: 20,
          name: '四川'
        },
        {
          id: 21,
          name: '贵州'
        },
        {
          id: 22,
          name: '云南'
        },
        {
          id: 23,
          name: '西藏'
        },
        {
          id: 24,
          name: '甘肃'
        },
        {
          id: 25,
          name: '青海'
        },
        {
          id: 26,
          name: '宁夏'
        },
      ],
      index2: 0,
      
      userMsg: {}
  },

  // 选择主科
  selectMainSubject(e){
    let subject = e.currentTarget.dataset['index']
    // console.log(subject)
    this.setData({
      mainSubject: subject
    })
  },
  //选择次科
  selectSecondSubject(e){
    let subject = e.currentTarget.dataset['index']
    var secondSubject = this.data.secondSubject;
    console.log(subject)
    if(this.data.secondSubject[0] == subject){
      secondSubject.splice(0,1)
    }else if(this.data.secondSubject[1] == subject){
      secondSubject.splice(1,2)
    }else {
      if(this.data.secondSubject.length + 1 > 2){
        wx:wx.showToast({
          title: '只允许选择两个次选科目',
          icon: 'none'
        })
      }else{
        secondSubject.push(subject);
      }
      
    }
    this.setData({
      secondSubject
    })
    console.log(this.data.secondSubject)
    console.log(this.data.secondSubject.length)
  },

  // 确认选科
  confirm(){
    if(this.data.mainSubject.length < 1 || this.data.secondSubject.length < 2){
      wx:wx.showToast({
        title: '请正确地选择您的高考科目!',
        icon: 'none'
      })
      return
    }
    this.setData({
      userMainSubject: this.data.mainSubject,
      userSecondSubject: this.data.secondSubject,
      showSubject: true
    })
    this.getRank();
    this.onClose();
  },

  // 科目选择框弹出与关闭
  showPopup(){
    this.setData({ 
      show: true,
      mainSubject: this.data.userMainSubject,
      secondSubject: this.data.userSecondSubject
    });
  },
  onClose() {
    this.setData({ show: false });
  },

  scoreToRank: function(e){
    if(e.detail.value >= 200 && e.detail.value <=750){
      this.getRank();
    }
  },

  bindPickerChange1: function(e) {
    this.setData({
      index1: e.detail.value
    })
  },

  bindPickerChange2: function(e) {
    this.setData({
      index2: e.detail.value
    })
  },

  login(){
    this.getuserInfo();
  },

  //提交校验
  submit(){
    if(this.data.score==""){
      wx:wx.showToast({
        title: '请输入您的分数',
        icon:"none"
      })
    }
    else if(this.data.score>750){
      wx:wx.showToast({
        title: '没有人能考超过满分啦！',
        icon:"none"
      })
    }
    else if(this.data.ranking==""){
      wx:wx.showToast({
        title: '请输入您的排位',
        icon:"none"
      })
    }
    else if(this.data.ranking<1){
      wx:wx.showToast({
        title: '你是考到天上去了才能考到这个排位？',
        icon:"none"
      })
    }
    else{
      this.setData({
        userMsg: {
          provinces:this.data.provinces[this.data.index1].name,
          mainSubject:this.data.userMainSubject,
          secondSubject:this.data.userSecondSubject,
          score:this.data.score,
          ranking:this.data.ranking
        }
      })
      this.postUserInfo()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onload: function(){
   
  },


  //获取用户信息的方法
 getuserInfo(){
   let ans = this;
   wx.getUserProfile({
     desc: '获取用户信息用于展示',
    // 用户确认获取信息
     success(res){
       let userInfo = res.userInfo 
       ans.setData({
           //确认获取信息 则设置isShow为true  显示用户信息
           isShow : true,
           name:userInfo.nickName,
           src:userInfo.avatarUrl
       })
       //将标志位信息和用户信息存入缓存
       //如果用户获取过一次  则直接显示头像和ID信息即可
       wx.setStorageSync('isShow', true)
       wx.setStorageSync('userInfo', userInfo)
       ans.getUserIsExist();
    },
    // 用户拒绝获取信息 给出提示
    fail(){
        wx:wx.showToast({
          title: '需要获取您的信息才可以继续哦',
          icon:"none"
        })
    }
   })
 },

  // 上传用户信息到服务器
  postUserInfo(){
    var dataMsg = {
      username: this.data.name,
      userImg: this.data.src,
      area: this.data.provinces[this.data.index1].name,
      mainSubject: this.data.userMainSubject,
      secondSubject: this.data.userSecondSubject,
      st_score: this.data.score,
      st_ranking: this.data.ranking
    };
    console.log(dataMsg);
      this.setData({
        isLoading: true
      })
      wx.showLoading({
        title: '请稍等...',
      })
      wx.request({
        url: app.globalData.requestUrl + '/user/preserveInfo',
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: dataMsg,
        success: (res) => {
          console.log(res.data)
          wx.hideLoading()
          this.setData({
            isLoading: false
          })
          if(res.data.code == 200 || res.data.code == 201){
            wx.setStorageSync("userMsg",this.data.userMsg)
            wx.reLaunch({
              url: '/pages/main/main',
            });
          }
          else if(res.data.code == 400 || res.data.code == 407 || res.data.code == 409){
            wx:wx.showToast({
              title: '服务器异常，请重试',
              icon: "none"
            })
            return
          }
          else if(res.data.code == 406){
            wx:wx.showToast({
              title: '请输入200~750区间的分数',
              icon: "none"
            })
            return
          }
          else if(res.data.code == 408){
            wx:wx.showToast({
              title: '请输入正确的分数与排位！',
              icon: "none"
            })
            return
          }
        },
        fail: (res) => {
          wx:wx.showToast({
            title: '网络异常，稍后再试',
            icon: "none"
          })
        },
        complete: () => {
          wx.hideLoading()
          this.setData({
            isLoading: false
          })
        }
      })
    },

    // 获取排名
    getRank(){
      wx.request({
        url: app.globalData.requestUrl + '/score/getRanking',
        method: 'GET',
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          subject: this.data.userMainSubject,
          st_score: this.data.score
        },
        success: (res) => {
          if(res.data.code == 206){
            console.log(res.data);
            this.setData({
              ranking: res.data.obj
            })
          }
          else if(res.data.code == 406){
            wx:wx.showToast({
              title: '请输入200~750区间的分数',
              icon: "none"
            })
            return
          }
          else if(res.data.code == 408){
            wx:wx.showToast({
              title: '请输入正确排位',
              icon: "none"
            })
            return
          }
        },
        fail: (res) => {
          wx:wx.showToast({
            title: '网络异常，请手动输入排位',
            icon: "none"
          })
        },
        complete: () => {

        }
      })
    },

  // 校验用户是否存在
  getUserIsExist(){
    this.setData({
      isLoading: true
    })
    wx.showLoading({
      title: '请稍等...',
    })
    console.log(this.data.name)
    wx.request({
      url: app.globalData.requestUrl + '/user/isExist',
      method: 'GET',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        username: this.data.name
      },
      success: (res) => {
        console.log(res)
        wx.hideLoading()
        this.setData({
          isLoading: false
        })
        if(res.data.code == 203){
          let secondSubject = [res.data.obj.secondSubject,res.data.obj.thirdSubject];
          let userMsg={
            provinces:res.data.obj.area,
            mainSubject:res.data.obj.mainSubject,
            secondSubject,
            score:res.data.obj.stScore,
            ranking:res.data.obj.stRanking
          }
          console.log(userMsg)
          wx.setStorageSync("userMsg",userMsg),
          wx.reLaunch({
            url: '/pages/main/main',
          })
        }
        else if(res.data.code == 402){
          
        }
        else if(res.data.code == 403){
          wx:wx.showToast({
            title: '服务器异常，请重试',
            icon: 'none'
          })
        }
      },
      fail: (res) => {
        wx:wx.showToast({
          title: '网络异常，稍后再试',
          icon: "none"
        })
      },
      complete: () => {
        // wx.hideLoading()
        // this.setData({
        //   isLoading: false
        // })
      }
    })
  }
})

